package com.fleapx.netty_learn.heart_beat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.Random;


/**
 * @version:: netty_heart
 * @description:
 * @create: 2021/12/5 2:57.
 */
public class HeartBeatClient {
    int port;
    Channel channel;
    Random random;

    public HeartBeatClient(int port) {
        this.port = port;
        random = new Random();
    }

    public static void main(String[] args) {
        HeartBeatClient heartBeatClient = new HeartBeatClient(9999);
        heartBeatClient.start();
    }

    private void start() {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors).channel(NioSocketChannel.class)
                    .handler(new HeartBeatClientInitor());
            connect(bootstrap,port);
            String text = "I am alive";
            while (channel.isActive()){
             sendMsg(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }

    private void sendMsg(String text)throws Exception {
        channel.writeAndFlush(text);
        int i = random.nextInt(10);
        System.out.println("client sent msg ,then sleep "+ i);
        Thread.sleep(i*1000);
    }

    public void connect(Bootstrap bootstrap, int port) throws Exception {
        channel = bootstrap.connect("localhost", 9999).sync().channel();
    }

    static class HeartBeatClientInitor extends ChannelInitializer<Channel> {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            pipeline.addLast(new HeartBeatClientHandler());
        }
    }
    static class HeartBeatClientHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
            System.out.println("client received:"+s);
            if(s!=null && s.equals("you are out")){
                System.out.println("server closed connection, so client will close too");
                channelHandlerContext.channel().closeFuture();
            }
        }
    }
}
